﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web;

namespace CodeCounsel.SharePoint2010.DigiD
{
    public static class Extensions
    {
        public static Dictionary<string, string> GetQuery(this UriBuilder builder)
        {
            Dictionary<string, string> query = null;
            if (builder.Query != null)
            {
                query = GetQuery(builder.Query);
            }
            else
            {
                query = new Dictionary<string, string>();
            }
            return query;
        }

        public static Dictionary<string, string> GetQuery(this Uri uri)
        {
            return GetQuery(uri.Query);
        }

        public static Dictionary<string, string> GetQuery(string queryText)
        {
            Dictionary<string, string> parameters = null;
            if (String.IsNullOrEmpty(queryText) == false)
            {
                parameters = queryText.TrimStart('?').Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
                  .Select(splitItem => splitItem.Split('='))
                  .Select(splitItems => new {
                      Key = splitItems[0],
                      Value = String.Join("=", splitItems.Skip(1).ToArray())
                  })
                  .ToDictionary(pair => pair.Key, pair => pair.Value);
            }
            else
            {
                parameters = new Dictionary<string, string>();
            }
            return parameters;
        }

        public static void SetQuery(this UriBuilder builder, Dictionary<string, string> query)
        {
            builder.Query = String.Join("&",
               query.Select(kvp => String.Format("{0}={1}", kvp.Key, kvp.Value)).ToArray());
        }
    }
}
